package actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import awesomeDocumentIO.AwesomeDocumentImporter;

import dialogs.NewFileDialog;
import document.AwesomeDocument;
import frame.AwesomeFrame;

import misc.Vals;

import textArea.AwesomeTextPanel;

/**
 * Displays the visual interface used to create a new document.
 * @author Brittin
 *
 */
public class NewFileAction extends AwesomeMenuAction {

	public NewFileAction(String name, String desc) {
		super(name, desc);
		putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_N));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		// Prompt them to save the older file if one is open and it is not yet
		// saved
		AwesomeTextPanel panel = this.getSelectedTextPanel(e);
		AwesomeFrame frame = this.getParentFrame(e);

		if (panel.isChanged()) {
			int response = JOptionPane.showConfirmDialog(null,
					Vals.saveChangesMessage);
			if (response == JOptionPane.OK_OPTION) {
				File file = frame.getCurrentFile();

				try {
					// Write the old file
					ActionFileIO.saveFile(file, panel.getTextPane().getText());
				} catch (IOException ex) {
					JOptionPane.showMessageDialog(null,
							Vals.fileWriteErrorMessage);
					// e.printStackTrace();
				}

			} else if (response == JOptionPane.CANCEL_OPTION) {
				return;
			}
		}

		// Prompt the user for the type of file they want to create.
		NewFileDialog dialog = new NewFileDialog(frame);
		dialog.setVisible(true);
		String filetype = dialog.getSelectedFileType();

		// Now create the new document
		if (filetype == null)
			return;

		// Load the document type and set it
		AwesomeDocument doc = AwesomeDocumentImporter
				.importDocumentType(filetype);

		if (doc == null) {
			JOptionPane
					.showMessageDialog(null,
							"Error: Could not file files associated with this document type.");
			return;
		}

		panel.setDocumentType(doc);
		frame.setTitle(Vals.mainFrameTitle + ": New");

		// Update the text panel
		panel.getTextPane().setText("");
		panel.setChanged(false);
		frame.setCurrentFile(null);
	}

}
